package gdufs.lkl.calculator;

import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;

public class CustomFunctionManagerActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_EDIT_FUNCTION = 1;
    private FunctionStorage functionStorage;
    private CustomFunctionAdapter adapter;
    private List<CustomFunction> functions;
    private CustomFunction selectedFunction;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_function_manager);

        // 设置工具栏
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        functionStorage = new FunctionStorage(this);
        functions = functionStorage.getFunctions();

        RecyclerView recyclerView = findViewById(R.id.recyclerViewFunctions);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new CustomFunctionAdapter(functions, this::showFunctionOptions);
        recyclerView.setAdapter(adapter);

        FloatingActionButton fab = findViewById(R.id.fab_add_function);
        fab.setOnClickListener(view -> addFunction());
    }

    private void addFunction() {
        Intent intent = new Intent(this, EditCustomFunctionActivity.class);
        startActivityForResult(intent, REQUEST_CODE_EDIT_FUNCTION);
    }

    private void showFunctionOptions(CustomFunction function) {
        selectedFunction = function;
        
        // 创建一个简单的弹出菜单，提供编辑、计算和删除选项
        androidx.appcompat.app.AlertDialog.Builder builder = new androidx.appcompat.app.AlertDialog.Builder(this);
        builder.setTitle(function.getName())
               .setItems(new String[]{"计算", "编辑", "删除"}, (dialog, which) -> {
                   switch (which) {
                       case 0: // 计算
                           calculateFunction(function);
                           break;
                       case 1: // 编辑
                           editFunction(function);
                           break;
                       case 2: // 删除
                           deleteFunction(function);
                           break;
                   }
               })
               .show();
    }

    private void calculateFunction(CustomFunction function) {
        Intent intent = new Intent(this, FunctionCalculatorActivity.class);
        intent.putExtra("functionId", function.getId());
        startActivity(intent);
    }

    private void editFunction(CustomFunction function) {
        Intent intent = new Intent(this, EditCustomFunctionActivity.class);
        intent.putExtra("functionId", function.getId());
        startActivityForResult(intent, REQUEST_CODE_EDIT_FUNCTION);
    }
    
    private void deleteFunction(CustomFunction function) {
        new androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("删除函数")
            .setMessage("确定要删除函数 " + function.getName() + " 吗？")
            .setPositiveButton("删除", (dialog, which) -> {
                functionStorage.deleteFunction(function.getId());
                functions.remove(function);
                adapter.notifyDataSetChanged();
                Toast.makeText(this, R.string.function_deleted, Toast.LENGTH_SHORT).show();
            })
            .setNegativeButton("取消", null)
            .show();
    }    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();
        
        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_switch_to_calculator) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.action_switch_to_scientific) {
            Intent intent = new Intent(this, ScientificCalculatorActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.action_switch_to_converter) {
            Intent intent = new Intent(this, ConverterActivity.class);
            startActivity(intent);
            finish();
            return true;
        } else if (id == R.id.action_custom_function) {
            // 已经在自定义函数页面，不操作
            return true;
        } else if (id == R.id.action_history) {
            Intent intent = new Intent(this, HistoryActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }
        
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_EDIT_FUNCTION && resultCode == RESULT_OK) {
            functions.clear();
            functions.addAll(functionStorage.getFunctions());
            adapter.notifyDataSetChanged();
        }
    }
}
